package com.android.photoassistant;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

@SuppressLint("ShowToast")
public class MyLocationActivity extends FragmentActivity implements LocationListener {
	
	GoogleMap map;
	ArrayList<LatLng> markerPoints;
	double mLatitude = 0;
    double mLongitude = 0;
    LocationManager locationManager;
    String provider;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_location);
        
        Log.d("Start", "Start");
        
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        
        if (status != ConnectionResult.SUCCESS) {
        	int requestCode = 10;
        	Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        	dialog.show();
        } else {
            markerPoints = new ArrayList<LatLng>();
            SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
            
            map = fm.getMap();
            if (map != null) {
            	map.setMyLocationEnabled(true);
            	
            	LocationManager service = (LocationManager)getSystemService(LOCATION_SERVICE);
            	boolean enableGPS = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
            	boolean enableWifi = service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            	if (!enableGPS) {
            		Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
            		Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            		startActivity(intent);
            	}
            	locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
            	Criteria criteria = new Criteria();
            	provider = locationManager.getBestProvider(criteria, true);
            	
            	locationManager.requestLocationUpdates(provider, 60000, 10, this);
            	
            	Location location = locationManager.getLastKnownLocation(provider);
            	
            	if (location != null) {
            		String text = "Latitude: " + mLatitude + "\nLongitude:" + mLongitude;
            		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
            		toast.show();
            		onLocationChanged(location);
            	}
            	map.setOnMapClickListener(new OnMapClickListener() {
					
					@Override
					public void onMapClick(LatLng arg0) {
						// TODO Auto-generated method stub
						markerPoints.add(arg0);
						MarkerOptions options = new MarkerOptions();
						
						options.position(arg0);
						options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
						
						map.addMarker(options);
					}
				});
            	
            	map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
					
					@Override
					public boolean onMarkerClick(Marker arg0) {
						LatLng startPoint = new LatLng(mLatitude, mLongitude);
						LatLng endPoint = arg0.getPosition();
						
						String url = getDirectionsUrl(startPoint, endPoint);
						
						DownloadTask downloadTask = new DownloadTask();
						downloadTask.execute(url);
						// TODO Auto-generated method stub
						return false;
					}
				});
            }
        }
    }

    private String getDirectionsUrl(LatLng startPoint, LatLng endPoint) {
		String str_start = "origin=" + startPoint.latitude + "," + startPoint.longitude;
		String str_end = "destination=" + endPoint.latitude + "," + endPoint.longitude;
		
		String sensor = "sensor=false";
		
		String parameters = str_start + "&" + str_end + "&" + sensor;
		String output = "json";
		String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
		
		return url;
	}
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		mLatitude = location.getLatitude();
		mLongitude = location.getLongitude();
		
		LatLng point = new LatLng(mLatitude, mLongitude);
		
		map.moveCamera(CameraUpdateFactory.newLatLng(point));
		map.animateCamera(CameraUpdateFactory.zoomTo(15));
		
		String text = "Latitude: " + mLatitude + "\nLongitude:" + mLongitude;
		Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
		toast.show();
		
//		MarkerOptions options = new MarkerOptions();
//		options.position(point);
//		
//		options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
//		map.addMarker(options);
	}


	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	private String downloadUrl(String strurl) throws IOException {
		String data = "";
		InputStream iStream = null;
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL(strurl);
			urlConnection = (HttpURLConnection)url.openConnection();
			
			urlConnection.connect();
			
			iStream = urlConnection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
			
			StringBuffer sb = new StringBuffer();
			
			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			data = sb.toString();
			br.close();
		} catch (Exception e) {
			// TODO: handle exception
			Log.d("Exception while downloading url", e.toString());
		} finally {
			iStream.close();
			urlConnection.disconnect();
		}
		return data;
	}
	
	private class DownloadTask extends AsyncTask<String, Void, String>
	{

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {
				data = downloadUrl(params[0]);
			} catch (Exception e) {
				// TODO: handle exception
				Log.d("Background Task",e.toString());
			}
			// TODO Auto-generated method stub
			return data;
		}
		@Override
		protected void onPostExecute(String result) {			
			super.onPostExecute(result);			
			
			ParserTask parserTask = new ParserTask();
			
			// Invokes the thread for parsing the JSON data
			parserTask.execute(result);
				
		}
	}
	
	private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>>
	{

		@Override
		protected List<List<HashMap<String, String>>> doInBackground(
				String... params) {
			JSONObject jObject;
			List<List<HashMap<String, String>>> routes = null;
			
			try {
				jObject = new JSONObject(params[0]);
				DirectionsJSONParser parser = new DirectionsJSONParser();
				
				routes = parser.parse(jObject);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			// TODO Auto-generated method stub
			return routes;
		}

		@Override
		protected void onPostExecute(List<List<HashMap<String, String>>> result) {
			// TODO Auto-generated method stub
			ArrayList<LatLng> points = null;
			PolylineOptions lineOptions = null;
			String distance = "";
			String duration = "";
			Context context = getApplicationContext();
			
			for (int i = 0; i < result.size(); i++) {
				points = new ArrayList<LatLng>();
				lineOptions = new PolylineOptions();
				
				List<HashMap<String, String>> path = result.get(i);
				
				for (int j = 0; j < path.size(); j++) {
					HashMap<String, String> point = path.get(j);
					
					if (j == 0) {
						distance = (String)point.get("distance");
						continue;
					} else if (j ==1) {
						duration = (String)point.get("duration");
						continue;
					}
					double lat = Double.parseDouble(point.get("lat"));
					double lng = Double.parseDouble(point.get("lng"));
					LatLng position = new LatLng(lat, lng);	
					
					points.add(position);
					
				}
				
				lineOptions.addAll(points);
				lineOptions.width(4);
				lineOptions.color(Color.RED);
			}
			
			CharSequence text = "Distance:" + distance + "\nDuration:" + duration;
			int duration_toast = Toast.LENGTH_SHORT;
			
			Toast toast = Toast.makeText(context, text, duration_toast);
			toast.show();
			
			map.addPolyline(lineOptions);
			
			
		}
		
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.d("Resume", "Resume");
		locationManager.requestLocationUpdates(provider, 500, 50, this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d("Pause", "Pause");
		locationManager.removeUpdates(this);
		//deleteCache(this);
	}
	
	public static void deleteCache(Context context) {
	    try {
	        File dir = context.getCacheDir();
	        if (dir != null && dir.isDirectory()) {
	            deleteDir(dir);
	        }
	    } catch (Exception e) {}
	}
	
	public static boolean deleteDir(File dir) {
	    if (dir != null && dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i = 0; i < children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	    return dir.delete();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.getParent().onBackPressed();
	}
	
	
}
